package com.ai.trickycards.widgets

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.res.use
import com.ai.trickycards.R
import com.ai.trickycards.databinding.LayoutPokerCardComposeViewBinding
import kotlin.math.roundToInt

class PokerCardComposeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val binding = LayoutPokerCardComposeViewBinding.inflate(LayoutInflater.from(context), this)
    val pokerCardViews = listOf(
        binding.poker01,
        binding.poker02,
        binding.poker03,
        binding.poker04,
        binding.poker05
    )

    private val density by lazy {
        context.resources.displayMetrics.density
    }

    var pokerWidth: Int = 0
        set(value) {
            field = value
            resize()
        }
    var pokerHeight: Int = 0
        set(value) {
            field = value
            resize()
        }

    private var designPokerWidth: Int = (72 * density).roundToInt()
    private var designPokerHeight: Int = (108 * density).roundToInt()
    private var designHorizontalGap: Int = (-20 * density).roundToInt()
    private val translationY01: Float = 2 * density
    private val translationY02: Float = 10 * density

    init {
        clipChildren = false

        context.obtainStyledAttributes(attrs, R.styleable.PokerCardComposeView).use {
            pokerWidth = it.getDimensionPixelOffset(R.styleable.PokerCardComposeView_pccvItemWidth, 0)
            pokerHeight = it.getDimensionPixelOffset(R.styleable.PokerCardComposeView_pccvItemHeight, 0)
        }
        resize()

    }

    var horizontalGap = 0
        private set

    private fun resize() {
        val scale = pokerWidth / 1f / designPokerWidth

        val translationYList = listOf(translationY02, translationY01, 0f, translationY01, translationY02).map { it * scale }
        pokerCardViews.forEachIndexed { index, pokerCardView ->
            val layoutParams = pokerCardView.layoutParams as LayoutParams
            layoutParams.width = pokerWidth
            layoutParams.height = pokerHeight
            pokerCardView.layoutParams = layoutParams
            pokerCardView.translationY = translationYList[index]
        }

        horizontalGap = (designHorizontalGap * scale).roundToInt()
        binding.flowPoker.setHorizontalGap(horizontalGap)
    }

}